package com.haredot.service.impl;

import com.haredot.controller.PreviewController;
import com.haredot.dto.SwiperDTO;
import com.haredot.entity.Advert;
import com.haredot.entity.Swiper;
import com.haredot.mapper.AdvertMapper;
import com.haredot.mapper.SwiperMapper;
import com.haredot.service.SwiperService;
import com.haredot.vo.R;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
public class SwiperServiceImpl implements SwiperService {

    @Resource
    private SwiperMapper swiperMapper ;

    @Resource
    private AdvertMapper advertMapper ;

    @Override
    public R<?> querySwipers() {

        List<SwiperDTO> swiperDTOS = swiperMapper.findSwipers() ;

        return R.<SwiperDTO>ok().data(swiperDTOS);
    }

    @Override
    public R<?> saveSwiper(Swiper swiper) {
        int len = this.swiperMapper.save(swiper) ;
        return len == 1 ? R.ok().build() : R.fail().build();
    }

    @Override
    public R<?> updateSwiper(Swiper swiper) {
        int len = this.swiperMapper.update(swiper) ;
        return len == 1 ? R.ok().build() : R.fail().build();
    }

    @Override
    public R<?> removeById(Long id) {
        int len = this.swiperMapper.deleteById(id) ;
        return len == 1 ? R.ok().build() : R.fail().build();
    }

    @Override
    public R<?> removeByIds(List<Long> ids) {
        int len = this.swiperMapper.batchDeleteByIds(ids) ;
        return len > 0 ? R.ok().build() : R.fail().build();
    }

    @Override
    public R<Map<String, Object>> querySwipersAndAdverts(String sysRemark) {

        // 查询所有的轮播图 和 随机查询一个广告位
        List<Swiper> swipers = swiperMapper.findAllSwiper(sysRemark);

        // 处理图片地址
        swipers.forEach(swiper -> {
            String uriString = MvcUriComponentsBuilder
                    .fromMethodName(PreviewController.class, "preview", swiper.getUrl(), "inline")
                    .build().toUriString();
            swiper.setUrl(uriString);
        });

        // 查询 一个广告位
        List<Advert> adverts =  advertMapper.findAllAdvert(sysRemark);

        adverts.forEach(ad -> {
            String uriString = MvcUriComponentsBuilder
                    .fromMethodName(PreviewController.class, "preview", ad.getUrl(), "inline")
                    .build().toUriString();
            ad.setUrl(uriString);
        });

        return R.<Map<String, Object>>ok().data(new HashMap<>(Map.of("swipers", swipers , "adverts", adverts)));
    }
}
